//
//  MYGAddCaseFilesCell.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/4/9.
//

import UIKit
import DGCollectionViewLeftAlignFlowLayout
import TZImagePickerController

class MYGAddCaseFilesCell: UITableViewCell {
    
    var selectImageBlock:(([UIImage]) -> ())?
    
    var videos: PHAsset?
    private var contents: [MYGFindSendImageCellModel] = []
    private var images: [UIImage] = []
    
    

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initUI()
        configCell()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI(){
        
        contentView.backgroundColor = .rgba(255, 255, 255, 1)
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16.5) 
            make.left.equalTo(20)
        }
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom)
            make.height.equalTo(96)
        }
    }
    
     lazy var titleLabel:UILabel = {
       let cont = UILabel()
        cont.font = .regular(14)
        cont.textColor = .rgba(80, 80, 80, 1)
        cont.text = "上传门诊病历/检查报告"
        return cont
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = DGCollectionViewLeftAlignFlowLayout()
        layout.itemSize = CGSize(width: 96, height: 96)
        layout.minimumLineSpacing = 14
        layout.minimumInteritemSpacing = 14
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellWithClass: MYGFindSendImageCell.self)
        cv.addObserver(self, forKeyPath: "contentSize", context: nil)
        cv.backgroundColor = .white
        return cv
    }()
    
    // MARK: - Cell
    private func configCell() {
        contents = []
        
        for image in images {
            let model = MYGFindSendImageCellModel()
            model.image = image
            model.removeAction = {[weak self] in
                self?.images.removeAll(image)
                if self?.videos != nil {
                    self?.videos = nil
                }
                self?.configCell()
            }
            contents.append(model)
        }
        
        if contents.count < 3 && videos == nil {
            let model = MYGFindSendImageCellModel()
            model.isAdd = true
            contents.append(model)
        }
        selectImageBlock?(images)
        collectionView.reloadData()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let keyPath = keyPath, keyPath == "contentSize" {
            collectionView.snp.remakeConstraints { make in
                make.left.right.equalToSuperview().inset(20)
                make.top.equalTo(titleLabel.snp.bottom).offset(5)
                make.height.equalTo(collectionView.contentSize.height)
            }
        }
    }
    
}
extension MYGAddCaseFilesCell: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        contents.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withClass: MYGFindSendImageCell.self, for: indexPath)
       
        cell.model = contents[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = contents[indexPath.row]
        if model.isAdd {
            let pick = TZImagePickerController(maxImagesCount: 4-contents.count, delegate: self)
            pick?.maxImagesCount = 4-contents.count
            if images.count > 0 {
                pick?.allowTakeVideo = false
                pick?.allowPickingVideo = false
            } else {
                pick?.allowTakeVideo = true
                pick?.allowPickingVideo = true
            }

            UIViewController.currentViewController?.navigationController?.present(pick!, animated: false)
        }
    }
}

extension MYGAddCaseFilesCell: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
        self.images.append(contentsOf: photos)
        
        configCell()
    }
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: PHAsset!) {
        self.images.append(coverImage)
        self.videos = asset
        
        configCell()
    }
    
}
